<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>HTML 转 PDF</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
          "Helvetica Neue", Arial, sans-serif;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        min-height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px;
      }

      .container {
        background: white;
        border-radius: 16px;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        padding: 40px;
        max-width: 600px;
        width: 100%;
      }

      h2 {
        color: #333;
        text-align: center;
        margin-bottom: 30px;
        font-size: 24px;
      }

      .upload-area {
        border: 3px dashed #cbd5e0;
        border-radius: 12px;
        padding: 60px 20px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
        background: #f7fafc;
        position: relative;
      }

      .upload-area:hover {
        border-color: #667eea;
        background: #edf2f7;
      }

      .upload-area.dragover {
        border-color: #667eea;
        background: #e6f0ff;
        transform: scale(1.02);
      }

      .upload-icon {
        font-size: 48px;
        margin-bottom: 16px;
        color: #667eea;
      }

      .upload-text {
        color: #4a5568;
        font-size: 16px;
        margin-bottom: 8px;
      }

      .upload-hint {
        color: #a0aec0;
        font-size: 14px;
      }

      #htmlFile {
        display: none;
      }

      .file-info {
        margin-top: 20px;
        padding: 16px;
        background: #e6f0ff;
        border-radius: 8px;
        display: none;
        align-items: center;
        gap: 12px;
      }

      .file-info.show {
        display: flex;
      }

      .file-icon {
        font-size: 24px;
      }

      .file-details {
        flex: 1;
      }

      .file-name {
        color: #2d3748;
        font-weight: 500;
        margin-bottom: 4px;
      }

      .file-size {
        color: #718096;
        font-size: 12px;
      }

      .remove-file {
        background: none;
        border: none;
        color: #e53e3e;
        cursor: pointer;
        font-size: 20px;
        padding: 4px;
        line-height: 1;
      }

      .remove-file:hover {
        color: #c53030;
      }

      #uploadBtn {
        width: 100%;
        margin-top: 20px;
        padding: 14px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
      }

      #uploadBtn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
      }

      #uploadBtn:active {
        transform: translateY(0);
      }

      #uploadBtn:disabled {
        background: #cbd5e0;
        cursor: not-allowed;
        box-shadow: none;
      }

      .loading {
        display: none;
        text-align: center;
        margin-top: 20px;
        color: #667eea;
      }

      .loading.show {
        display: block;
      }

      .mode-switch {
        margin-bottom: 20px;
        display: flex;
        gap: 10px;
        background: #f7fafc;
        padding: 4px;
        border-radius: 8px;
      }

      .mode-btn {
        flex: 1;
        padding: 10px;
        border: none;
        background: transparent;
        color: #4a5568;
        border-radius: 6px;
        cursor: pointer;
        font-size: 14px;
        font-weight: 500;
        transition: all 0.3s ease;
      }

      .mode-btn.active {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
      }

      .path-input-container {
        display: none;
        margin-bottom: 20px;
      }

      .path-input-container.show {
        display: block;
      }

      .path-input {
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #cbd5e0;
        border-radius: 8px;
        font-size: 14px;
        transition: all 0.3s ease;
      }

      .path-input:focus {
        outline: none;
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
      }

      .path-hint {
        margin-top: 8px;
        font-size: 12px;
        color: #718096;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h2>📄 HTML 转 PDF</h2>

      <div class="mode-switch">
        <button class="mode-btn active" id="uploadMode">📤 上传文件</button>
        <button class="mode-btn" id="directMode">📁 直接转换</button>
      </div>

      <div class="path-input-container" id="pathInputContainer">
        <input
          type="text"
          class="path-input"
          id="pathInput"
          placeholder="输入 HTML 文件路径，例如：test.html"
        />
        <div class="path-hint">💡 输入 static 目录下的文件名或路径</div>
      </div>

      <div class="upload-area" id="uploadArea">
        <div class="upload-icon">📁</div>
        <div class="upload-text">点击选择文件或拖拽文件到此处</div>
        <div class="upload-hint">支持 .html 文件</div>
        <input type="file" id="htmlFile" accept=".html" />
      </div>

      <div class="file-info" id="fileInfo">
        <div class="file-icon">📄</div>
        <div class="file-details">
          <div class="file-name" id="fileName"></div>
          <div class="file-size" id="fileSize"></div>
        </div>
        <button class="remove-file" id="removeFile" title="移除文件">✕</button>
      </div>

      <button id="uploadBtn" disabled>上传并生成 PDF</button>

      <div class="loading" id="loading">⏳ 正在生成 PDF...</div>
    </div>

    <script>
      const uploadArea = document.getElementById("uploadArea");
      const fileInput = document.getElementById("htmlFile");
      const fileInfo = document.getElementById("fileInfo");
      const fileName = document.getElementById("fileName");
      const fileSize = document.getElementById("fileSize");
      const removeFileBtn = document.getElementById("removeFile");
      const uploadBtn = document.getElementById("uploadBtn");
      const loading = document.getElementById("loading");

      let selectedFile = null;
      let currentMode = "upload"; // 'upload' or 'direct'

      // 点击上传区域触发文件选择
      uploadArea.addEventListener("click", () => {
        fileInput.click();
      });

      // 文件选择变化
      fileInput.addEventListener("change", (e) => {
        handleFile(e.target.files[0]);
      });

      // 阻止默认拖拽行为
      ["dragenter", "dragover", "dragleave", "drop"].forEach((eventName) => {
        uploadArea.addEventListener(eventName, preventDefaults, false);
      });

      function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
      }

      // 拖拽高亮效果
      ["dragenter", "dragover"].forEach((eventName) => {
        uploadArea.addEventListener(eventName, () => {
          uploadArea.classList.add("dragover");
        });
      });

      ["dragleave", "drop"].forEach((eventName) => {
        uploadArea.addEventListener(eventName, () => {
          uploadArea.classList.remove("dragover");
        });
      });

      // 处理拖拽文件
      uploadArea.addEventListener("drop", (e) => {
        const files = e.dataTransfer.files;
        if (files.length > 0) {
          const file = files[0];
          if (file.name.endsWith(".html")) {
            handleFile(file);
          } else {
            alert("请上传 .html 文件！");
          }
        }
      });

      // 处理文件
      function handleFile(file) {
        if (!file) return;

        selectedFile = file;
        fileName.textContent = file.name;
        fileSize.textContent = formatFileSize(file.size);
        fileInfo.classList.add("show");
        uploadBtn.disabled = false;
      }

      // 格式化文件大小
      function formatFileSize(bytes) {
        if (bytes === 0) return "0 Bytes";
        const k = 1024;
        const sizes = ["Bytes", "KB", "MB", "GB"];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return (
          Math.round((bytes / Math.pow(k, i)) * 100) / 100 + " " + sizes[i]
        );
      }

      // 移除文件
      removeFileBtn.addEventListener("click", (e) => {
        e.stopPropagation();
        selectedFile = null;
        fileInput.value = "";
        fileInfo.classList.remove("show");
        uploadBtn.disabled = true;
      });

      // 模式切换
      const uploadModeBtn = document.getElementById("uploadMode");
      const directModeBtn = document.getElementById("directMode");
      const pathInputContainer = document.getElementById("pathInputContainer");
      const pathInput = document.getElementById("pathInput");

      uploadModeBtn.addEventListener("click", () => {
        currentMode = "upload";
        uploadModeBtn.classList.add("active");
        directModeBtn.classList.remove("active");
        uploadArea.style.display = "block";
        pathInputContainer.classList.remove("show");
        uploadBtn.disabled = !selectedFile;
      });

      directModeBtn.addEventListener("click", () => {
        currentMode = "direct";
        directModeBtn.classList.add("active");
        uploadModeBtn.classList.remove("active");
        uploadArea.style.display = "none";
        fileInfo.classList.remove("show");
        pathInputContainer.classList.add("show");
        uploadBtn.disabled = !pathInput.value.trim();
      });

      // 监听路径输入变化
      pathInput.addEventListener("input", () => {
        if (currentMode === "direct") {
          uploadBtn.disabled = !pathInput.value.trim();
        }
      });

      // 上传并生成 PDF
      uploadBtn.addEventListener("click", async () => {
        if (currentMode === "upload") {
          // 上传模式
          if (!selectedFile) {
            alert("请先选择一个 HTML 文件！");
            return;
          }

          uploadBtn.disabled = true;
          loading.classList.add("show");

          try {
            const formData = new FormData();
            formData.append("file", selectedFile);

            const response = await fetch("/api/html-to-pdf", {
              method: "POST",
              body: formData,
            });

            if (!response.ok) {
              throw new Error("生成 PDF 失败");
            }

            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = selectedFile.name.replace(".html", ".pdf");
            a.click();
            window.URL.revokeObjectURL(url);

            alert("✅ PDF 生成成功！");
          } catch (error) {
            alert("❌ " + error.message);
          } finally {
            loading.classList.remove("show");
            uploadBtn.disabled = false;
          }
        } else {
          // 直接转换模式
          const filePath = pathInput.value.trim();
          if (!filePath) {
            alert("请输入文件路径！");
            return;
          }

          uploadBtn.disabled = true;
          loading.classList.add("show");

          try {
            const response = await fetch(
              `/api/html-to-pdf/direct?filePath=${encodeURIComponent(
                filePath
              )}`,
              {
                method: "POST",
              }
            );

            if (!response.ok) {
              const errorText = await response.text();
              throw new Error(errorText || "生成 PDF 失败");
            }

            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            const fileName = filePath.split("/").pop().replace(".html", ".pdf");
            a.download = fileName;
            a.click();
            window.URL.revokeObjectURL(url);

            alert("✅ PDF 生成成功！");
          } catch (error) {
            alert("❌ " + error.message);
          } finally {
            loading.classList.remove("show");
            uploadBtn.disabled = false;
          }
        }
      });
    </script>
  </body>
</html>
